package ru.ifmo.tanya.keepers;

import ru.ifmo.tanya.core.calls.Call;
import ru.ifmo.tanya.core.users.User;

import java.util.HashMap;
import java.util.Map;

/**
 * User: nikart
 * Date: 5/18/13
 * Time: 7:52 PM
 */
public class User2CallMapKeeper {

    private static final Map<User, Call> user2CallMap = new HashMap<>();

    private static final Map<Call, Long> call2RegisteringTimestamp = new HashMap<>();

    private static final Map<Call, User> call2User = new HashMap<>();

    public synchronized boolean routeCallToUser(Call call, User user) {
        if (user2CallMap.containsKey(user)) {
            return false;
        }
        user2CallMap.put(user, call);
        call2User.put(call, user);
        call2RegisteringTimestamp.put(call, System.currentTimeMillis());
        return true;
    }

    public Call getHoldingCallForUser(User user) {
        return user2CallMap.get(user);
    }

    public void removeHoldingCallForUser(User user) {
        Call call = user2CallMap.remove(user);
        if (call != null) {
            call2User.remove(call);
            call2RegisteringTimestamp.remove(call);
        }
    }

    public Long getHoldTimeForCall(Call call) {
        Long startTime = call2RegisteringTimestamp.get(call);
        if (startTime != null) {
            return System.currentTimeMillis() - startTime;
        } else {
            return 0L;
        }
    }

    public User getUserToAnswerCall(Call call) {
        return call2User.get(call);
    }
}
